package com.jboost.modules.app.exception;

import com.google.common.collect.Maps;
import com.jboost.common.api.vo.Result;
import com.jboost.modules.app.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public Object handleException(HttpServletRequest request, HttpServletResponse response, Throwable exception) {
        String ip = RequestUtil.getRemoteAddr(request);
        String uri = RequestUtil.trimURI(request);
        log.error(String.format("ip地址%s,访问地址%s", ip, uri), exception);
        String msg = "系统异常" ;
        String description = exception.getCause() == null ? exception.getMessage() : exception.getCause().getMessage();
        if (exception instanceof BindException) {
            BindException bindException = (BindException) exception;
            msg = bindException.getFieldError().getDefaultMessage();
        } else if (exception instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException) exception;
            msg = validException.getBindingResult().getFieldError().getDefaultMessage();
        }
        if (exception instanceof RuntimeException){
            msg = exception.getMessage();
        }
        return Result.error(msg);
    }

}
